package cn.edu.ptu.jobfairs.web;

import cn.edu.ptu.jobfairs.basic.common.DataResult;
import cn.edu.ptu.jobfairs.basic.common.Errors;
import cn.edu.ptu.jobfairs.basic.common.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.xml.crypto.Data;
import java.io.File;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by Lin Chenxiao on 2020-05-31
 **/
@RestController
public class CommonController {
    @Value("${config.upload}")
    private String updatePath;
    private final Set<String> uploading = new HashSet<>();

    @GetMapping("/login")
    public Result login() {
        return Result.fail(Errors.NOT_LOGGED);
    }

    @PostMapping("/f/update")
    public Result update(MultipartFile file) {
        String path = null;
        try {
            int i = 0;
            File dest;
            synchronized (uploading) {
                do {
                    dest = new File(updatePath + (path = String.valueOf(++i) + '/' + file.getOriginalFilename()));
                }
                while (uploading.contains(path) || dest.exists() && dest.isFile());
                uploading.add(path);
            }
            File dir = new File(updatePath + i);
            if ((!dir.exists() || !dir.isDirectory()) && !dir.mkdirs())
                return Result.fail(Errors.SERVER_ERROR, "上传失败, 服务器无法创建文件夹");
            file.transferTo(dest);
            return DataResult.ok(i);
        }
        catch (Exception e) {
            return Result.fail(Errors.SERVER_ERROR, "上传失败, 服务器无法存放");
        }
        finally {
            if (path != null) {
                synchronized (uploading) {
                    uploading.remove(path);
                }
            }
        }
    }
}
